package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
public class ProducerQuickStart {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.kafka的配置信息
        Properties properties = new Properties();
        //kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.237.137:9092");
        //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,5);
        //消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");

        properties.put(ProducerConfig.ACKS_CONFIG,"all");

        //数据压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"snappy");

        //消息value的序列化器
        //2.生产者对象
        KafkaProducer<String,String> kafkaProducer = new KafkaProducer<String,String>(properties);
        //封装发送的消息
        ProducerRecord<String,String>  producerRecord = new ProducerRecord<String,String>("itheima-topic","100001","hello kafka");
        //3.发送消息
        //同步方式发送消息
//        RecordMetadata recordMetadata = kafkaProducer.send(producerRecord).get();
//
//        System.out.println(recordMetadata.offset());

        kafkaProducer.send(producerRecord,new Callback(){
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if (e != null) {
                    e.printStackTrace();
                } else {
                    System.out.println(recordMetadata.offset());
                }
            }
        });
        //4.关闭消息通道，必须关闭，否则消息发送不成功
        kafkaProducer.close();
    }

}
